package com.qf.JDBC2;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * @author wangyu
 * @Classname: DBUtitls
 * @Description: TEST
 * @date 2022-04-04 14:24
 */
public class DBUtitls {
    private static final Properties PROPERTIES = new Properties();//存储文件的map集合

    //    类加载一次
    static {
        InputStream is = DBUtitls.class.getResourceAsStream("/db.properties");
        try {
            PROPERTIES.load(is); //通过流，添加配置文件中的内容信息
            Class.forName(PROPERTIES.getProperty("driver"));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

    }

    //    1链接
    public static Connection getConnection() {
        Connection connection = null;//修改后
        try {
            connection = DriverManager.getConnection(PROPERTIES.getProperty("url"), PROPERTIES.getProperty("username"), PROPERTIES.getProperty("password"));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

    //    2释放资源
    public static void closeAll(Connection connection, Statement statement, ResultSet resultSet) {
        try {
            if (resultSet != null) {
                resultSet.close();
            }
            if (statement != null) {
                statement.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
